package top.igotcha.chapter.chapter3;

/**
 * @author Gotcha
 * @date 2021/2/28
 * @describe 带超时判断的保护性暂停
 */
public class GuardedSuspension02 {
    public static void main(String[] args) {
        String hello = "hello thread!";
        NewGuarded guarded = new NewGuarded();
        new Thread(()->{
            System.out.println("想要得到结果");
            synchronized (guarded) {
                System.out.println("结果是："+guarded.getResponse(2000));
            }
            System.out.println("得到结果");
        }).start();

        //new Thread(()->{
        //    System.out.println("设置结果");
        //    synchronized (guarded) {
        //        guarded.setResponse(hello);
        //    }
        //}).start();
    }
}
class NewGuarded extends Guarded {
    public Object getResponse(long time) {
        synchronized (this) {
            //获取开始时间
            long currentTime = System.currentTimeMillis();
            //用于保存已经等待了的时间
            long passedTime = 0;
            while(response == null) {
                //看经过的时间-开始时间是否超过了指定时间
                long waitTime = time -passedTime;
                if(waitTime <= 0) {
                    break;
                }
                try {
                    //等待剩余时间
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //获取当前时间
                passedTime = System.currentTimeMillis()-currentTime;
            }
        }
        return response;
    }

}

